<script setup lang="ts">
import dayjs from 'dayjs'
import MpHtml from 'mp-html/src/uni-app/components/mp-html/mp-html.vue'
import { fetchIntercityTicketSetDetailAPI } from '@/apis/fetchIntercityTicketSetDetail'
import { type CreateIntercityOrderAPIParams, createIntercityOrderAPI } from '@/apis/createIntercityOrder'
import type { IntercityTicket, IntercityTicketSet } from '@/types/api'
import { payIntercityTicketAPI } from '@/apis/payIntercityTicket'
import { uploadFileAPI } from '@/apis/uploadFile'
import { useUserInfoStore } from '@/store/userInfo'
import { IntercityOrderType } from '@/types/enum'
import useStatusBarHeight from '@/composables/statusBarHeight'
import { useOrdersTabSelectionStore } from '@/store/ordersTabSelection'
import { useGeneralConfigStore } from '@/store/generalConfig'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const generalConfigStore = useGeneralConfigStore()
const ordersTabSelectionStore = useOrdersTabSelectionStore()

/* -------------------------------- 导航栏 START ------------------------------- */
const statusBarHeight = useStatusBarHeight()
// 是否显示状态栏背景
const isShowNavBg = ref(false)
// 监听页面滚动，更新状态栏背景可见性
onPageScroll((e) => {
  const toggle = useThrottleFn(() => isShowNavBg.value = e.scrollTop > 16, 100)
  toggle()
})
// 将状态栏背景可见性提供给状态栏组件
provide(isShowNavigationBarBackgroundKey, isShowNavBg)
/* --------------------------------- 导航栏 END -------------------------------- */

const id = ref('')
const orderType = ref<IntercityOrderType>()

// 车票详情和列表数据
const detail = ref<{
  intercity_info: IntercityTicketSet
  intercity_detail: IntercityTicket[]
}>()

// 当前订单类型的票价
const price = computed(() => {
  return (orderType.value === IntercityOrderType.城际购票 ? detail.value?.intercity_info.passenger_price : detail.value?.intercity_info.delivery_price) || '0'
})

/* ------------------------------- 选择日期 START ------------------------------- */
// 选中的日期
const selectedDay = ref(dayjs(Date.now()).format('YYYY-MM-DD'))
// 用于显示的选中的日期
const displayedSelectedDay = computed(() => compareDate(selectedDay.value))

// 日历组件 ref
const calendarRef = ref<any>(null)
// 将今天作为可选日期的开始，因为无法选择已经过去的日期
const minDate = dayjs(Date.now()).format('YYYY-MM-DD')

// 日历组件选择日期的回调
function handleChooseDate(e: any) {
  selectedDay.value = dayjs(e.fulldate).format('YYYY-MM-DD')
  fetchDetail()
}
/* -------------------------------- 选择日期 END -------------------------------- */

// 选中的车票
const selectedTicket = ref<IntercityTicket>()

// 根据选中的日期和车票时间点计算出当前订单的时间，'YYYY-MM-DD HH:mm' 格式
const orderTime = computed(() => `${selectedDay.value} ${selectedTicket.value?.clock}`)

// 页面加载时请求数据
onLoad(async (options) => {
  if (!options?.order_type || !options?.id) {
    uni.showToast({ title: '获取数据失败', icon: 'none' })
    return
  }
  id.value = options.id
  orderType.value = Number(options.order_type)
  fetchDetail()
})

async function fetchDetail() {
  detail.value = await fetchIntercityTicketSetDetailAPI({
    id: id.value,
    days: selectedDay.value,
  }, userInfoStore.userInfo!.token!)
    .then(res => res.data?.data)
}

// 表单 ref
const formRef = ref<any>()
// 表单数据
const formData = ref({
  num: 1,
  passengers_name: '',
  passengers_mobile: '',
  goods_type: '',
  images: [] as string[],
  remark: '',
  real_start_place: '',
  real_end_place: '',
})
// 校验规则
const rules = computed(() => {
  if (orderType.value === IntercityOrderType.城际购票) {
    return {
      real_start_place: [
        { required: true, message: '请输入出发地', trigger: ['blur', 'change'] },
      ],
      real_end_place: [
        { required: true, message: '请输入目的地', trigger: ['blur', 'change'] },
      ],
      passengers_name: [
        { required: true, message: '请输入乘客姓名', trigger: ['blur', 'change'] },
      ],
      passengers_mobile: [
        { required: true, message: '请输入乘客电话', trigger: ['blur', 'change'] },
      ],
    }
  }
  else {
    return {
      real_start_place: [
        { required: true, message: '请输入出发地', trigger: ['blur', 'change'] },
      ],
      real_end_place: [
        { required: true, message: '请输入目的地', trigger: ['blur', 'change'] },
      ],
      passengers_name: [
        { required: true, message: '请输入乘客姓名', trigger: ['blur', 'change'] },
      ],
      passengers_mobile: [
        { required: true, message: '请输入乘客电话', trigger: ['blur', 'change'] },
      ],
      goods_type: [
        {
          required: true,
          transform(value: string[]) {
            return value.join(',')
          },
          message: '请选择物品类型',
          trigger: ['blur', 'change'],
        },
      ],
    }
  }
})

function handleBack() {
  if (selectedTicket.value)
    selectedTicket.value = undefined
  else
    router.back()
}

/* ------------------------------ 选择物品类型 START ------------------------------ */
function handleSelectGoodsType(type: string) {
  formData.value.goods_type = type
}
/* ------------------------------- 选择物品类型 END ------------------------------- */

/* ------------------------------- 选择照片 START ------------------------------- */
/**
 * @description 处理选择照片事件
 */
function handlePickImage() {
  uni.chooseFile({
    type: 'image',
    complete: (result) => {
      (result.tempFiles as File[]).forEach(async (file) => {
        const res = await uploadFileAPI({
          tempFilePath: (file as any).path,
          fileType: 'image',
        }, userInfoStore.userInfo!.token!)
        if (res.data) {
          const resData = JSON.parse(res.data)
          formData.value.images.push(resData.data.fullurl)
        }
      })
    },
  })
}

/**
 * @description 处理删除照片事件
 */
function handleDeleteImage(picture: string) {
  formData.value.images = formData.value.images
    .filter(item => item !== picture)
}
/* -------------------------------- 选择照片 END -------------------------------- */

const isShowConfirmModal = ref(false)

/**
 * @description 下单。
 */
const handleSubmit = useThrottleFn(() => {
  isShowConfirmModal.value = false
  formRef.value.validate()
    .then(async () => {
      let query: CreateIntercityOrderAPIParams = {
        type: orderType.value === IntercityOrderType.城际购票 ? '2' : '1',
        id: selectedTicket.value!.id.toString(),
        num: formData.value.num.toString(),
        passengers_name: formData.value.passengers_name,
        passengers_mobile: formData.value.passengers_mobile,
        start_time: orderTime.value,
        real_start_place: formData.value.real_start_place,
        real_end_place: formData.value.real_end_place,
      }
      if (orderType.value === IntercityOrderType.城际捎件) {
        query = {
          ...query,
          goods_type: formData.value.goods_type,
          images: formData.value.images.join(','),
          remark: formData.value.remark,
        }
      }
      const res = await createIntercityOrderAPI(query, userInfoStore.userInfo!.token!)
      if (res.data?.code !== 1)
        return
      const payRes = await payIntercityTicketAPI({ id: res.data.data }, userInfoStore.userInfo!.token!)
      if (payRes.data?.code !== 1)
        return
      WeixinJSBridge.invoke('getBrandWCPayRequest', {
        appId: payRes.data.data.appId,
        timeStamp: payRes.data.data.timeStamp,
        nonceStr: payRes.data.data.nonceStr,
        package: payRes.data.data.package,
        signType: payRes.data.data.signType,
        paySign: payRes.data.data.paySign,
      }, (res: any) => {
        if (res.err_msg === 'get_brand_wcpay_request:ok') {
          uni.showModal({
            title: '购买成功',
            confirmText: '查看详情',
            success: (success) => {
              if (success.confirm) {
                ordersTabSelectionStore.selectedSegmentIndex = 1
                ordersTabSelectionStore.selectedTabIndex = 0
                router.pushTab('orders')
              }
            },
            showCancel: false,
          })
        }
        else { uni.showToast({ title: '支付失败', icon: 'none' }) }
      })
    })
    .catch((errors: AnyObject[]) => {
      if (errors.length > 0)
        uni.showToast({ title: errors[0].message, icon: 'none' })
    })
}, 1000)
</script>

<template>
  <Spacer height="24" />
  <view :style="{ height: `${statusBarHeight + 44}px` }" />
  <NavigationBar
    title="购买车票"
    :front-color="'#333333' as any"
    :is-show-back-button="true"
    use-custom-back-event
    @back="handleBack"
  />
  <view class="px-24rpx">
    <view class="mb-24rpx rounded-30rpx bg-white px-30rpx pb-37rpx pt-53rpx">
      <view class="flex items-center justify-between">
        <Address dot-color="#3F8BF6">
          <view class="text-30rpx">
            起点：{{ detail?.intercity_info.start_place || '未知' }}
          </view>
        </Address>
        <view class="relative">
          <image
            class="h-9rpx w-136rpx"
            src="@/static/images/arrow_right_long.png"
          />
          <view class="absolute text-center text-24rpx text-#999999 font-medium x-center -top-12rpx">
            出发
          </view>
        </view>
        <Address dot-color="#FA662F">
          <view class="text-30rpx">
            终点：{{ detail?.intercity_info.end_place || '未知' }}
          </view>
        </Address>
      </view>
      <Spacer height="30" />
      <view class="rounded-30rpx bg-#F6F8FC p-30rpx">
        <view class="flex items-center justify-between">
          <view class="flex items-center">
            <image
              class="h-29rpx w-33rpx"
              src="@/static/images/ticket.png"
            />
            <Spacer width="12" />
            <view class="text-28rpx text-#333333">
              城际合成{{ orderType === IntercityOrderType.城际购票 ? '购票' : '捎件' }}（定金）
            </view>
          </view>
          <view class="text-32rpx text-#F53B25" @tap="calendarRef.open()">
            ¥{{ price }}/人
          </view>
        </view>
      </view>
    </view>
    <!-- 没有选择车票时显示车票列表 -->
    <view v-if="!selectedTicket" class="rounded-30rpx bg-white px-30rpx py-40rpx">
      <view class="flex items-center justify-between">
        <view class="flex items-center">
          <image
            class="h-34rpx w-34rpx"
            src="@/static/images/clock.jpg"
          />
          <Spacer width="14" />
          <view class="text-28rpx text-[#333333] font-bold">
            出发时间
          </view>
        </view>
        <view class="text-28rpx text-#999999 font-medium" @tap="calendarRef.open()">
          {{ displayedSelectedDay || '请选择出发时间' }}
        </view>
      </view>
      <Spacer height="10" />
      <view v-if="detail?.intercity_detail.length === 0" class="h-300rpx flex items-center justify-center text-28rpx text-#999999">
        暂无当日车票
      </view>
      <block v-else>
        <view v-for="item in detail?.intercity_detail" :key="item.id" class="mt-24rpx flex items-center justify-between rounded-30rpx bg-#F6F8FC px-30rpx py-28rpx">
          <view class="flex items-center text-28rpx text-#333333 font-medium leading-28rpx">
            <view>{{ item.clock || '--:--' }}</view>
            <Spacer width="15" />
            <view>余票数：{{ orderType === IntercityOrderType.城际购票 ? item.passenger_left_num : item.delivery_left_num }}</view>
          </view>
          <RGButton :disabled="orderType === IntercityOrderType.城际购票 ? item.passenger_left_num === 0 : item.delivery_left_num === 0" type="primary" size="small" corner="full" @tap="selectedTicket = item">
            购票
          </RGButton>
        </view>
      </block>
    </view>
    <!-- 选择车票后显示表单 -->
    <uv-form v-else ref="formRef" :model="formData" :rules="rules">
      <view class="rounded-30rpx bg-white">
        <ListCell>
          <template #label>
            <view class="flex items-center">
              <image
                class="h-34rpx w-34rpx"
                src="@/static/images/clock.jpg"
              />
              <Spacer width="14" />
              <view class="text-28rpx text-[#333333] font-bold">
                出发时间
              </view>
            </view>
          </template>
          <view class="text-28rpx text-#333333 leading-28rpx">
            {{ orderTime }}
          </view>
        </ListCell>
        <Divider width="642" />
        <ListCell>
          <template #label>
            <view class="flex items-center">
              <image
                class="h-34rpx w-34rpx"
                src="@/static/images/tickets.png"
              />
              <Spacer width="14" />
              <view class="text-28rpx text-[#333333] font-bold">
                购票张数
              </view>
            </view>
          </template>
          <uv-number-box :max="orderType === IntercityOrderType.城际购票 ? selectedTicket.passenger_left_num : selectedTicket.delivery_left_num" bg-color="rgba(0, 0, 0, 0)" @change="(e: any) => formData.num = Number(e.value)">
            <template #minus>
              <view class="h-42rpx w-42rpx flex items-center justify-center rounded-10rpx text-28rpx" :class="formData.num <= 1 ? 'bg-#F0F0F0 text-#999999' : 'bg-#3F8BF6 text-white'">
                -
              </view>
            </template>
            <template #plus>
              <view class="h-42rpx w-42rpx flex items-center justify-center rounded-10rpx bg-#3F8BF6 text-28rpx text-white">
                +
              </view>
            </template>
          </uv-number-box>
        </ListCell>
        <Divider width="642" />
        <ListCell>
          <template #label>
            <view class="flex items-center">
              <image
                class="h-40rpx w-34rpx"
                src="@/static/images/marker_black.png"
              />
              <Spacer width="14" />
              <view class="text-28rpx text-[#333333] font-bold">
                出发地（必填）
              </view>
            </view>
          </template>
          <ListInput v-model="formData.real_start_place" type="text" placeholder="请输入出发地" />
        </ListCell>
        <Divider width="642" />
        <ListCell>
          <template #label>
            <view class="flex items-center">
              <image
                class="h-40rpx w-34rpx"
                src="@/static/images/marker_black.png"
              />
              <Spacer width="14" />
              <view class="text-28rpx text-[#333333] font-bold">
                目的地（必填）
              </view>
            </view>
          </template>
          <ListInput v-model="formData.real_end_place" type="text" placeholder="请输入目的地" />
        </ListCell>
        <Divider width="642" />
        <ListCell>
          <template #label>
            <view class="flex items-center">
              <image
                class="h-34rpx w-34rpx"
                src="@/static/images/profile.png"
              />
              <Spacer width="14" />
              <view class="text-28rpx text-[#333333] font-bold">
                联系人姓名
              </view>
            </view>
          </template>
          <ListInput v-model="formData.passengers_name" type="text" placeholder="请输入联系人姓名" />
        </ListCell>
        <Divider width="642" />
        <ListCell>
          <template #label>
            <view class="flex items-center">
              <image
                class="h-34rpx w-34rpx"
                src="@/static/images/phone.png"
              />
              <Spacer width="14" />
              <view class="text-28rpx text-[#333333] font-bold">
                联系电话
              </view>
            </view>
          </template>
          <ListInput v-model="formData.passengers_mobile" type="number" placeholder="请输入联系人电话" />
        </ListCell>
        <Divider v-if="orderType === IntercityOrderType.城际购票" width="642" />
        <ListCellColumn v-if="orderType === IntercityOrderType.城际购票" label="备注信息">
          <textarea
            v-model="formData.remark"
            class="h-180rpx rounded-20rpx bg-#F3F3F3 p-30rpx text-28rpx text-#333333 leading-40rpx"
            placeholder="行李物品等其他备注..."
            placeholder-class="text-#999999"
          />
        </ListCellColumn>
      </view>
      <Spacer height="24" />
      <view v-if="orderType === IntercityOrderType.城际捎件" class="rounded-30rpx bg-white">
        <ListCellColumn label="物品类型">
          <view class="grid grid-cols-3 grid-rows-2 gap-32rpx">
            <RGButton
              size="medium"
              corner="full"
              :type="formData.goods_type.includes('食品饮料') ? 'primary' : 'secondary'"
              @tap="handleSelectGoodsType('食品饮料')"
            >
              食品饮料
            </RGButton>
            <RGButton
              size="medium"
              corner="full"
              :type="formData.goods_type.includes('鲜花') ? 'primary' : 'secondary'"
              @tap="handleSelectGoodsType('鲜花')"
            >
              鲜花
            </RGButton>
            <RGButton
              size="medium"
              corner="full"
              :type="formData.goods_type.includes('蛋糕') ? 'primary' : 'secondary'"
              @tap="handleSelectGoodsType('蛋糕')"
            >
              蛋糕
            </RGButton>
            <RGButton
              size="medium"
              corner="full"
              :type="formData.goods_type.includes('家居家纺') ? 'primary' : 'secondary'"
              @tap="handleSelectGoodsType('家居家纺')"
            >
              家居家纺
            </RGButton>
            <RGButton
              size="medium"
              corner="full"
              :type="formData.goods_type.includes('服饰鞋帽') ? 'primary' : 'secondary'"
              @tap="handleSelectGoodsType('服饰鞋帽')"
            >
              服饰鞋帽
            </RGButton>
            <RGButton
              size="medium"
              corner="full"
              :type="formData.goods_type.includes('文件证照') ? 'primary' : 'secondary'"
              @tap="handleSelectGoodsType('文件证照')"
            >
              文件证照
            </RGButton>
          </view>
        </ListCellColumn>
        <Divider width="642" />
        <ListCellColumn label="上传图片">
          <PictureGrid
            :pictures="formData.images"
            mode="edit"
            :width="642"
            :cols="4"
            @pick-image="handlePickImage"
            @delete="handleDeleteImage"
          />
        </ListCellColumn>
        <Divider width="642" />
        <ListCellColumn label="备注信息">
          <textarea
            v-model="formData.remark"
            class="h-180rpx rounded-20rpx bg-#F3F3F3 p-30rpx text-28rpx text-#333333 leading-40rpx"
            placeholder="请输入您的备注信息..."
            placeholder-class="text-#999999"
          />
        </ListCellColumn>
      </view>
    </uv-form>
    <Spacer height="180" />
  </view>
  <view v-if="selectedTicket" class="fixed bottom-0 w-full flex items-center justify-between bg-#FFFFFF px-24rpx py-16rpx x-center">
    <view class="flex items-center">
      <image
        class="h-30rpx w-30rpx"
        src="@/static/images/warning_orange_circle.png"
      />
      <Spacer width="8" />
      <view class="text-33rpx text-#333333">
        总计:
        <text class="text-#F53B25 font-bold">
          ¥{{ Number(price) * formData.num }}
        </text>
      </view>
    </view>
    <RGButton size="large" corner="large" :width="460" @tap="isShowConfirmModal = true">
      立即下单
    </RGButton>
  </view>

  <uv-calendars
    ref="calendarRef"
    :date="selectedDay"
    :insert="false"
    round="20rpx"
    :start-date="minDate"
    @confirm="handleChooseDate"
  />

  <uv-overlay :show="isShowConfirmModal" @tap="isShowConfirmModal = false">
    <uv-transition mode="zoom-in" :show="isShowConfirmModal">
      <view class="relative h-screen w-screen">
        <view class="absolute left-50% top-50% -translate-50%">
          <Dialog
            :has-icon="false"
            :show-cancel-button="false"
            title="下单须知"
            confirm-button-label="我已确认"
            @confirm="handleSubmit"
          >
            <template #content>
              <scroll-view scroll-y class="h-400rpx">
                <MpHtml :content="generalConfigStore.generalConfig?.base.find(el => el.title === '下单须知')?.content || ''" class="mx-24rpx" />
              </scroll-view>
            </template>
          </Dialog>
        </view>
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'buyIntercityTicket'
style:
  navigationStyle: 'custom'
</route>
